'use client'

import { useEffect, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Loader2, XCircle, CheckCircle, Mail } from 'lucide-react'

interface InviteData {
  email: string
  project: {
    id: string
    name: string
    description?: string
  }
  role: string
  roleText: string
  message?: string
  expires: string
  inviter: {
    id: string
    name: string
    image?: string
  }
}

export default function AcceptInvitePage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { data: session, status } = useSession()
  const token = searchParams.get('token')

  const [invite, setInvite] = useState<InviteData | null>(null)
  const [loading, setLoading] = useState(true)
  const [accepting, setAccepting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState(false)

  console.log('AcceptInvitePage 组件加载:', { token, sessionStatus: status })

  // 获取邀请详情
  useEffect(() => {
    console.log('useEffect 触发:', { token })
    
    if (!token) {
      console.log('没有 token，设置错误')
      setError('缺少邀请令牌')
      setLoading(false)
      return
    }

    fetchInviteDetails()
  }, [token])

  const fetchInviteDetails = async () => {
    console.log('开始获取邀请详情:', token)
    
    try {
      const url = `/api/project/invite/accept?token=${token}`
      console.log('请求 URL:', url)
      
      const response = await fetch(url)
      console.log('响应状态:', response.status)
      
      const data = await response.json()
      console.log('响应数据:', data)

      if (!response.ok) {
        throw new Error(data.message || '获取邀请详情失败')
      }

      if (data.success) {
        setInvite(data.data)
        console.log('邀请详情设置成功:', data.data)
      } else {
        throw new Error(data.message)
      }
    } catch (err: any) {
      console.error('获取邀请详情失败:', err)
      setError(err.message || '获取邀请详情失败')
    } finally {
      setLoading(false)
    }
  }

  // 接受邀请
  const handleAcceptInvite = async () => {
    if (!token || accepting) return

    console.log('开始接受邀请:', { token, userEmail: session?.user?.email })
    
    setAccepting(true)
    try {
      const response = await fetch('/api/project/invite/accept', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token }),
      })

      console.log('接受邀请响应状态:', response.status)
      
      const data = await response.json()
      console.log('接受邀请响应数据:', data)

      if (!response.ok) {
        throw new Error(data.message || '接受邀请失败')
      }

      if (data.success) {
        setSuccess(true)
        console.log('邀请接受成功，准备跳转到:', `/project/${data.data.projectId}`)
        // 3秒后重定向到项目页面
        setTimeout(() => {
          router.push(`/project/${data.data.projectId}`)
        }, 3000)
      } else {
        throw new Error(data.message)
      }
    } catch (err: any) {
      console.error('接受邀请失败:', err)
      setError(err.message || '接受邀请失败')
    } finally {
      setAccepting(false)
    }
  }

  // 页面加载状态
  if (loading) {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin" />
            <span className="ml-2">加载邀请详情...</span>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 错误状态
  if (error) {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center text-red-600">
              <XCircle className="h-5 w-5 mr-2" />
              邀请无效
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground mb-4">{error}</p>
            <Button onClick={() => router.push('/dashboard')} className="w-full">
              返回首页
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 成功状态
  if (success) {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center text-green-600">
              <CheckCircle className="h-5 w-5 mr-2" />
              邀请接受成功
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground mb-4">
              您已成功加入项目，即将跳转到项目页面...
            </p>
            <div className="flex items-center justify-center">
              <Loader2 className="h-4 w-4 animate-spin mr-2" />
              <span className="text-sm">跳转中...</span>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 需要登录
  if (status === 'loading') {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin" />
            <span className="ml-2">检查登录状态...</span>
          </CardContent>
        </Card>
      </div>
    )
  }

  if (!session) {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardHeader>
            <CardTitle>需要登录</CardTitle>
            <CardDescription>
              请先登录以接受项目邀请
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button 
              onClick={() => router.push(`/auth/signin?callbackUrl=${encodeURIComponent(window.location.href)}`)}
              className="w-full"
            >
              登录
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 邮箱不匹配
  if (invite && session.user?.email !== invite.email) {
    return (
      <div className="container max-w-md mx-auto py-12">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center text-orange-600">
              <Mail className="h-5 w-5 mr-2" />
              邮箱不匹配
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground mb-2">
              此邀请是发送给 <strong>{invite.email}</strong> 的
            </p>
            <p className="text-muted-foreground mb-4">
              但您当前登录的账号是 <strong>{session.user.email}</strong>
            </p>
            <div className="space-y-2">
              <Button 
                onClick={() => router.push(`/auth/signin?callbackUrl=${encodeURIComponent(window.location.href)}`)}
                className="w-full"
              >
                切换账号
              </Button>
              <Button 
                variant="outline" 
                onClick={() => router.push('/dashboard')} 
                className="w-full"
              >
                返回首页
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 显示邀请详情
  return (
    <div className="container max-w-md mx-auto py-12">
      <Card>
        <CardHeader>
          <CardTitle>项目邀请</CardTitle>
          <CardDescription>
            您收到了一个项目协作邀请
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {invite && (
            <>
              <div className="text-center">
                <h3 className="text-lg font-semibold">{invite.project.name}</h3>
                {invite.project.description && (
                  <p className="text-muted-foreground text-sm mt-1">
                    {invite.project.description}
                  </p>
                )}
              </div>

              <div className="border rounded p-3 bg-muted/20">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">邀请角色:</span>
                  <span className="font-medium">{invite.roleText}</span>
                </div>
                <div className="flex items-center justify-between text-sm mt-1">
                  <span className="text-muted-foreground">邀请人:</span>
                  <span className="font-medium">{invite.inviter.name}</span>
                </div>
              </div>

              {invite.message && (
                <div className="border rounded p-3 bg-blue-50">
                  <p className="text-sm text-blue-800">{invite.message}</p>
                </div>
              )}

              <Button 
                onClick={handleAcceptInvite} 
                disabled={accepting}
                className="w-full"
              >
                {accepting ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin mr-2" />
                    接受中...
                  </>
                ) : (
                  '接受邀请'
                )}
              </Button>

              <Button 
                variant="outline" 
                onClick={() => router.push('/dashboard')} 
                className="w-full"
              >
                取消
              </Button>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
} 
